/**
 * hybrid
 */


'use strict'
;(function(win){
    function Hybrid(){
        var self = this;
        if ('WebViewJavascriptBridge' in win) {
            if(!self.device){
                getDeviceInfo();
            }else{
                self.bridge = win['WebViewJavascriptBridge'];
            }
        } else {
            document.addEventListener('WebViewJavascriptBridgeReady', function () {
                var bridge = win['WebViewJavascriptBridge'];
                bridge.init(function (message, responseCallback) {
                    var data = {'Javascript Responds': 'Wee!'};
                    responseCallback(data)
                });
                getDeviceInfo(bridge);
            }, false)
        }

        function getDeviceInfo(bridge){
            bridge.send({
                handlerName: 'Action',
                data: {
                    action: 'Core',
                    method: 'getDeviceInfo',
                    params: null
                }
            }, function(result){
                self.bridge = bridge;
                self.device = result["data"];
                self.dispatchEvent('hybridReady');
            });
        }
    }

    Hybrid.prototype = {
        /**
         * @var {WebViewJavascriptBridge}
         */
        bridge: null,
        plugin: {},
        device: {},
        /**
         * 是否已准备就绪
         * @param {Function} callback
         */
        ready: function(callback){
            var self = this;
            if(self.bridge && self.device){
                typeof callback === 'function' && callback.call(self, self.bridge);
            }else{
                self.addEventListener('hybridReady', function(){
                    typeof callback === 'function' && callback.call(self, self.bridge);
                });
            }
        },

        /**
         * 添加事件监听
         * @param eventName
         * @param handler
         */
        addEventListener: function(eventName, handler){
            document.addEventListener('hybrid:' + eventName, handler);
        },

        /**
         * 取消事件监听
         * @param eventName
         * @param handler
         */
        removeEventListener: function(eventName, handler){
            document.removeEventListener('hybrid:' + eventName, handler)
        },

        /**
         * 触发实际
         * @param {String} eventName
         * @param {*} [data]
         * @param {HTMLDocument} [dom]
         */
        dispatchEvent: function(eventName, data, dom){
            var readyEvent = document.createEvent('Events');
            readyEvent.initEvent('hybrid:' + eventName, false, true);
            readyEvent.bridge = this.bridge;
            if(data)readyEvent.data = data;
            if(dom && 'dispatchEvent' in dom){
                dom.dispatchEvent(readyEvent);
            }else {
                document.dispatchEvent(readyEvent);
            }
        },

        /**
         * 注册一个函数供 Native 调用
         * @param {String} name 名称
         * @param {Function} handler
         */
        registerHandler: function(name, handler){
            this.ready(function(bridge){
                bridge.registerHandler(name, handler);
            });
        },

        /**
         * 调用 Native 提供的函数
         * @param {String} name 名称
         * @param {*} params 参数
         * @param {Function} callback
         */
        callHandler: function(name, params, callback){
            this.ready(function(bridge){
                bridge.send({
                    handlerName: name,
                    data: params
                }, callback);
            });
        },

        callAction: function(action, params, callback){
            if(!action || action.indexOf('/') === -1)return;
            action = action.split('/');
            hybrid.callHandler('Action', {
                action: action[0],
                method: action[1],
                params: params
            }, callback);
        },

        /**
         * 获取设备信息
         * @param {Function} [callback]
         */
        getDeviceInfo: function (callback) {
            hybrid.callAction('Core/getDeviceInfo', null, function (result) {
                typeof callback === 'function' && callback(result.status, result.data);
            });
        },
        /**
         * 获取网络状态
         * @param callback
         */
        getNetworkStatus: function(callback){
            hybrid.callAction('Core/getNetworkStatus', null, function (result) {
                typeof callback === 'function' && callback(result.status, result.data);
            });
        }
    };

    if (typeof win.hybrid === 'undefined'){
        var hybrid = new Hybrid();

        hybrid.registerHandler('dispatchEvent', function(result){
            if(result && result.event){
                hybrid.dispatchEvent(result.event, result.data);
            }
        });

        hybrid.addEventListener('PlatformsInfoUpdate', function(e){
            alert('PlatformsInfoUpdate : \n' + JSON.stringify(arguments))
        });

        hybrid.addEventListener('networkChanged', function(e){
            if(e.data.status)
                hybrid.device.networkState = e.data.status;
        });

        win.Hybrid = hybrid;

        win.onerror = function(e){
            alert(e);
        }
    }

})(window);
